package fr.jade.console.core;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import fr.jade.base.JadeBaseObject;
import fr.jade.console.cmd.Boot;
import fr.jade.console.cmd.Call;
import fr.jade.console.cmd.Cd;
import fr.jade.console.cmd.Connect;
import fr.jade.console.cmd.Exit;
import fr.jade.console.cmd.GetEnvVar;
import fr.jade.console.cmd.Lc;
import fr.jade.console.cmd.Ls;
import fr.jade.console.cmd.PrintEnv;
import fr.jade.console.cmd.PrintLevel;
import fr.jade.console.cmd.Pwd;
import fr.jade.console.cmd.SetAttribute;
import fr.jade.console.cmd.SetEnvVar;
import fr.jade.console.cmd.Source;
import fr.jade.console.cmd.SwitchLevel;
import fr.jade.util.JadeException;

public class JTerm extends JadeBaseObject{

  protected Map<String, Command> commands = null;
	protected Environment env = null;
	
	public JTerm(){
	  this.commands = new HashMap<String, Command>();
		this.env = new Environment();
		env.setEnvVar( "curent", new Object() );
		env.setEnvVar( "shell", this );
		registerCommands();
	}
	
	public JTerm( String[] args ){
		// not yet implemented
	}
	
	protected void registerCommands(){
	 new Boot().register(commands);
	 new Call().register(commands);
	 new Cd().register(commands);
	 new Connect().register(commands);
	 new Exit().register(commands);
	 new GetEnvVar().register(commands);
	 new Lc().register(commands);
	 new Ls().register(commands);
	 new PrintEnv().register(commands);
	 new PrintLevel().register(commands);
	 new Pwd().register(commands);
	 new SetAttribute().register(commands);
	 new SetEnvVar().register(commands);
	 new Source().register(commands);
	 new SwitchLevel().register(commands);
	 new Help().register(commands);
	}
	
	protected Map<String, Command> getConsoleCommands(){
	  return commands;
	}
	public void start(String[] args){
	  for(String cmdLine : args){
	    try{
        evaluateCmd( cmdLine );
      }catch(Throwable e){
        e.printStackTrace();
      }
	  }
		try{
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			while(true){
				log( " >" );
				String cmdLine = in.readLine();
				if ( !cmdLine.equals( "" ) ){
					try{
						evaluateCmd( cmdLine );
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
			
		}catch(Exception e){
			log("Fatal error in JTerm");
			e.printStackTrace();
		}
	}
	
	public void evaluateCmd(String cmdLine){
		String[] cmd = cmdLine.split(" ");
		try{
			Command c = commands.get(cmd[0]);
			if(c == null) {
			  System.err.println("JTerm: "+cmd[0]+" command not found");
			}else{
			  c.execute(cmd, env);
			}
		}catch(Throwable e){
			System.out.println("JTerm # Error");
			if(e instanceof JadeException){
			  log((JadeException)e);
			}else{
			  e.printStackTrace();
			}
		}
	}
}
